<template>
  <main-menu/>
  <div>
    <div class="center-container">
      <el-collapse v-model="activeNames" class="center-page" accordion>
        <div align="right" style="height: 40px;">
          <div style="float: left;height: 40px;font-weight:bold;font-size: larger">
            公开数据集
          </div>
          <p/>
        </div>
        <el-collapse-item accordion v-for="ds in ds_table" :key="ds.ds_id" class="collapse-type" align="left">
          <template #title>
            <i class="fa fa-database"></i>&emsp;{{ ds.ds_name }}
          </template>
          <el-table :data="[ds]" border style="width: 100%">
            <el-table-column prop="username" label="创建者" width="100" align="center"></el-table-column>
            <el-table-column prop="ds_id" label="数据集ID" width="100" align="center"></el-table-column>
            <el-table-column prop="ds_number" label="图片数量" width="100" align="center"></el-table-column>
            <el-table-column prop="ds_length" label="图片长度" width="100" align="center"></el-table-column>
            <el-table-column prop="ds_width" label="图片宽度" width="100" align="center"></el-table-column>
            <el-table-column prop="verify" label="验证码" width="180" align="center">
              <template v-slot="scope">
                {{ scope.row.verify }}
                <el-button type="text" align="right" size="mini" @click="handleCopy(scope.$index, scope.row)"> 复制
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="数据集描述" align="center" width="200">
              <template v-slot="scope">
                <el-button size="mini" type="primary" @click="handleDisplay(scope.row)">
                  <el-icon class="fa fa-eye" style="vertical-align: middle;"/>
                  <span style="vertical-align: middle;"> MarkDeep 查看 </span>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column prop="process" label="采集进度" width="140" align="center">
              <el-progress type="circle" :percentage=ds.process :color="colors" width="48"
                           style="margin-left:-55px"></el-progress>
              <el-button @click="showChart(ds)" type="text" size="mini"
                         style="min-height: 48px;position: absolute;padding-left: 10px"> 查看详情
              </el-button>
            </el-table-column>
            <el-table-column prop="operation" label="操作" align="center">
              <template v-slot="scope">
                <el-button size="mini" type="primary" @click="handleDownload(scope.row)">
                  <el-icon class="fa fa-download" style="vertical-align: middle;"/>
                  <span style="vertical-align: middle;"> 下载 </span>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
    <el-dialog v-model="dialogMarkdown2Visible" title="预览数据集描述文档(MarkDeep)" width="50%">
      <div style="width: 100%;height: 400px">
        <iframe id="markdeeppage2" designMode='on' :srcdoc="tmpdoc" height="100%" width="100%"
                style="float:right"></iframe>
      </div>
    </el-dialog>
    <el-dialog v-model="dialogTableVisible">
      <div style="margin-left: 50px">
        <v-chart class="chart" autoresize :option="chart_option"/>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MainMenu from "@/components/MainMenu";
import {ElMessage} from "element-plus";
import {get} from "@/utils/http";
import {ref} from "vue";

// 引入饼状图组件
require('echarts/lib/chart/pie')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')

export default {
  name: 'PublicDataset',
  data() {
    return {
      tmpdoc: '', // 预览 markdeep 文件
      activeNames: ['1'], // 默认展开的标签页
      copyData: null, // 校验码复制按钮复制的值
      ds_table: [], // 用户所有的数据集及其配置信息
      dialogMarkdown2Visible: false, // 预览 markdeep 对话框是否可见
      dialogTableVisible: false, // Echarts对话框是否可见
      // 进度条的渐变色
      colors: [
        {color: '#f56c6c', percentage: 5},
        {color: '#f5976c', percentage: 15},
        {color: '#e6a23c', percentage: 25},
        {color: '#c2a25e', percentage: 35},
        {color: '#3db264', percentage: 45},
        {color: '#66c4b5', percentage: 55},
        {color: '#5eb3be', percentage: 65},
        {color: '#567cb4', percentage: 75},
        {color: '#5071f1', percentage: 90},
        {color: '#856fd3', percentage: 100}
      ],
      chart_option: null,
    }
  },
  components: {
    MainMenu
  },
  created() {
    let footer = document.getElementById('footer')
    footer.innerHTML = "<div style=\"font-size: 10px; margin-top: 40px\"><hr><center><p style=\"font-size: 10px\">Author : Hanyu Su, Haotian Wang (CEO), Tianyi Guan, Yiming Li (COO), Yunsong Jia (CTO) </p><p>Power by : Vue 3.0 & Springboot.&emsp;&emsp;Arranged in alphabetical order.</p></center></div>"
    // 加载用户所有图像数据集的信息
    this.getDataset();
  },
  methods: {
    /**
     * @description: 获取用户所有的图像数据库及其配置信息
     * @return void
     */
    async getDataset() {
      let that = this;
      let tmp_label_num_pair_list = new Array();
      let tmp_label_list = new Array();
      let tmp_sum_list = new Array();
      get('/Selectpublicnum', { }).then(function (res) {
        // 对后端传来的数据格式进行解析
        for (let key in res.data) {
          tmp_label_num_pair_list.push(that.getMapData1(res.data[key]));
          tmp_label_list.push(that.getMapData2(res.data[key]));
          tmp_sum_list.push(that.getSum(res.data[key]));
        }
      })
      let cnt = 0;
      setTimeout(function () {
        get('/getpublicdatasetmess', { }).then(function (res) {
          if (res.code === 1) {
            // 遍历后端传来的数据库配置信息，将其逐个加入到前端表格中
            res.data.forEach(function (item) {
              var tmp = {
                username: item.username,
                ds_name: item.datasetName,
                ds_id: item.datasetid,
                ds_number: item.count,
                ds_length: item.photo_height,
                ds_width: item.photo_width,
                verify: item.verify,
                description: item.datasetDescription,
                chart_option: that.getChart(tmp_label_list[cnt], tmp_label_num_pair_list[cnt]), // 绘制饼图
                dialogTableVisible: false,
                process: ((tmp_sum_list[cnt] * 100) / item.count).toFixed(1), // 计算进度并设置采集进度条显示一位小鼠
              };
              that.ds_table.push(tmp);
              cnt = cnt + 1;
            })
          }
        })
      }, 500);
    },
    /**
     * @description: 数据格式转换 [{num: a, label: b}] -> [{value: a, name: b}]，方便进行饼图绘制
     * @param {res}  待转换的数据
     * @return {mapped_data}
     */
    getMapData1(res) {
      let mapped_data = []
      for (let item in res) {
        mapped_data.push({value: res[item]["num"], name: res[item]["label"]})
      }
      return mapped_data
    },
    /**
     * @description: 得到所有标签 [{num: a, label: b}] -> [b]，方便进行饼图绘制
     * @param {res}  待转换的数据
     * @return {mapped_data}
     */
    getMapData2(res) {
      let mapped_data = []
      for (let item in res) {
        mapped_data.push(res[item]["label"])
      }
      return mapped_data
    },
    /**
     * @description: 求和函数
     * @param {res}  待求和的数据
     * @return {sum}
     */
    getSum(res) {
      let sum = 0
      for (let item in res) {
        sum = sum + res[item]["num"];
      }
      return sum
    },
    /**
     * @description: 饼图绘制函数
     * @param {v_label}  标签
     * @param {v_data}  数据
     * @return {ref}
     */
    getChart(v_label, v_data) {
      // 对目前还未收集到图像的数据库进行特殊处理
      if (v_label.length <= 0) {
        v_label.push('无');
        v_data.push({value: 0, name: '无'});
      }
      return ref({
        title: {
          text: '图像采集详细信息', // 主标题
          x: 'center', // x轴方向对齐方式
        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          orient: 'vertical',
          x: 'left',      //可设定图例在左、右、居中
          y: 'center',     //可设定图例在上、下、居中
          padding: [0, 0, 0, 70],   //可设定图例[距上方距离，距右方距离，距下方距离，距左方距离]
        },
        series: [
          {
            name: '图像采集详细信息',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: v_data,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    },
    handleCopy(index, row) {
      this.copyData = row.verify;
      this.copy(this.copyData)
    },
    handleDisplay(row) {
      let that = this;
      that.tmpdoc = that.getMarkdeep2(row.description);
      that.dialogMarkdown2Visible = true;
    },
    /**
     * @description: 获取 markdeep 渲染后的文本 (预览文档时)
     * @param {txt}   待渲染的文本(实际上是数据库描述信息 description)
     * @return {he + txt + fo}
     */
    getMarkdeep2(txt) {
      var he = "<meta charset=\"utf-8\" emacsmode=\"-*- markdown -*-\"> <link rel=\"stylesheet\" href=\"https://casual-effects.com/markdeep/latest/apidoc.css?\">",
          fo = "<style class=\"fallback\">body{visibility:hidden}</style><script>markdeepOptions={tocStyle:'medium'};<" + "/script><script src=\"https://casual-effects.com/markdeep/latest/markdeep.min.js\" charset=\"utf-8\"><" + "/script>";
      return he + "\n\n" + txt + "\n\n" + fo;
    },
    /**
     * @description: 用户下载相应的图像数据集
     * @param {row}  用户希望下载的数据集所在行
     * @return void
     */
    handleDownload(row) {
      ElMessage.warning({
        showClose: true,
        message: "后台正在压缩您需要的数据集，请耐心等待，不要重复点击！",
        type: "warning",
        center: true
      })
      // 调用后端 datasetdownload 方法，其中返回的 msg 中存储了压缩数据集的 url 地址
      get('/datasetdownload', {
        datasetid: row.ds_id,
      }).then(function (res) {
        if (res.code === 1) {
          let url = res.msg
          window.open(url)
        } else {
          ElMessage.error({
            showClose: true,
            message: "下载失败",
            type: "error",
            center: true
          })
        }

      })
    },
    /**
     * @description: 拷贝表格中的“校验码”文本信息的具体方法
     * @param {row}  待拷贝数据所在的行
     * @return void
     */
    copy(data) {
      let url = data;
      let oInput = document.createElement('input');
      oInput.value = url;
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象
      // 执行浏览器复制命令
      document.execCommand("Copy");
      this.$message({
        message: '复制成功',
        type: 'success'
      });
      oInput.remove()
    },
    showChart(ds) {
      let that = this;
      that.chart_option = ds.chart_option
      that.dialogTableVisible = true
    }
  }
}
</script>

<style onload>
body {
  color: #fff;
  background: none;
}
</style>

<style scoped>
.center-container {
  width: 100%;
  height: 100%;
}

.center-page {
  -webkit-border-radius: 5px;
  border-radius: 5px;
  margin: 50px auto;
  width: 90%;
  padding: 35px 35px 15px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
  opacity: 0.95
}

.collapse-type >>> .el-collapse-item__header {
  font-size: 20px !important;
}
</style>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.chart {
  width: 100%;
  height: 250px;
}
</style>
